package org.xqh.study.leetcode.algorithm.twopointer;

/**
 * @ClassName LongestSubstringTwoDistinct
 * @Description https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters/
 * @Author xuqianghui
 * @Date 2021/2/12 22:18
 * @Version 1.0
 */
public class LongestSubstringTwoDistinct {

    /**
     * 给定一个字符串 s ，找出 至多 包含两个不同字符的最长子串 t ，并返回该子串的长度。
     *
     */

    public static void main(String[] args) {
        String s = "abbe";
        System.out.println(lengthOfLongestSubstringTwoDistinct(s));
    }

    public static int lengthOfLongestSubstringTwoDistinct(String s) {
        int res = 0;
        char[] arr = s.toCharArray();
        if(arr.length <= 2){
            return arr.length;
        }

        int left = 0;//左指针
        int right = 0;//右指针
        int len = arr.length;
        int[] freq = new int[128];//记录 字符出现频数
        int count = 0;//记录当前 窗口 不同字符个数
        while (right < len){
            if(freq[arr[right]] == 0){
                count ++;
            }
            freq[arr[right]]++;
            right ++;
            if(count <= 2){
                res = Math.max(right - left, res);
            }
            while (count > 2){
                if(freq[arr[left]] == 1){
                    count --;
                }
                freq[arr[left]]--;
                left ++;
            }
        }


        return res;
    }
}
